import { useEffect, useState } from "react";
import style from "./index.module.css";
import Navbar from "../../compoents/Navbar";
import { SearchBar, Toast } from "antd-mobile";
import { Tabs, Empty } from "antd-mobile";
import { DeleteOutline, QuestionCircleOutline } from "antd-mobile-icons";
import { useNavigate } from "react-router-dom";
// import { CloseCircleOutline } from "antd-mobile-icons";
import Zonghe from "../../compoents/Zonghe/Index";
import Books from "../../compoents/Books/Index";
import Doctor from "../../compoents/Doctor/Index";
import Hospital from "../../compoents/Hospital/Index";
import Soco from "../../compoents/Soco/Index";
import { Dialog } from "antd-mobile";
import { useDebunce } from "../../utils/useDebunce";
function Index() {
  const navigate = useNavigate();
  const [value, setValue] = useState("");
  const [searchVal, setSearchValue] = useState("");
  const [hasResult, setHasResult] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [history, setHistory] = useState<string[]>([]);
  const [activeTab, setActiveTab] = useState("1");

  



  // 读取历史
  useEffect(() => {
    try {
      const raw = localStorage.getItem("search_history");
      setHistory(raw ? JSON.parse(raw) : []);
    } catch {
      setHistory([]);
    }
  }, []);

  const persistHistory = (list: string[]) => {
    setHistory(list);
    try {
      localStorage.setItem("search_history", JSON.stringify(list));
    } catch (e) {
      console.warn("persist history failed", e);
    }
  };

  const saveHistory = (term: string) => {
    const t = term.trim();
    if (!t) return;
    const next = [t, ...history.filter((h) => h !== t)].slice(0, 10);
    persistHistory(next);
  };

  const clearHistory = () => {
    persistHistory([]);
    try {
      localStorage.removeItem("search_history");
    } catch (e) {
      console.warn("clear history failed", e);
    }
  };

  const handleClearConfirm = async () => {
    const result = await Dialog.confirm({
      title: "提示",
      content: "确定清空全部搜索记录?",
      cancelText: "取消",
      confirmText: "确定",
    });
    if (result) {
      clearHistory();
    }
  };

  const handleChipClick = (t: string) => {
    setValue(t);
    // 直接触发搜索逻辑
    triggerSearch(t);
  };

  const triggerSearch = (term: string) => {
    const trimmed = term.trim();
    if (trimmed === "") {
      setValue("");
      setSearchValue("");
      setHasResult(false);
      setIsSearching(false);
      return;
    }
    setHasResult(false);
    setIsSearching(true);
    setSearchValue(trimmed);
    saveHistory(trimmed);
  };

  const Search = useDebunce(async () => {
    if (!value) Toast.show("请输入搜索内容");
    triggerSearch(value);
  }, 1000);

  // 切换tab的函数
  const handleTabChange = (tabKey: string) => {
    setActiveTab(tabKey);
  };
  return (
    <div className={style.searchBgcolor}>
      <Navbar
        title={
          <div className={style.searIcon}>
            <SearchBar
              value={value}
              onChange={setValue}
              onSearch={Search}
              onClear={() => {
                setValue("");
                setHasResult(false);
                setSearchValue("");
                setIsSearching(false);
              }}
              placeholder="请输入内容"
              style={{ width: "80vw" }}
            />{" "}
            <span className={style.sou} onClick={() => Search()}>
              搜索
            </span>{" "}
          </div>
        }
        showBack
        onBack={() => navigate(-1)}
      />


      {/* <SideBar activeKey={activeKey} onChange={setActiveKey}>
        {keshi.length > 0 &&
          keshi.map((item, index) => (
            <SideBar.Item key={index} title={item.adminname}></SideBar.Item>
          ))}
      </SideBar>

          <div>
            <List>
              {keshi[Number(activeKey)]?.adminchildrenname.map((item)=>(
                <List.Item key={item}>
                   {item.adminchildrenname}
                </List.Item>
              ))}
            </List>
          </div> */}




      <div className={style.searchBox}>
        {/* 最近搜索：仅在输入为空且内容区隐藏时显示 */}
        {value.trim() === "" &&
          !(searchVal && hasResult) &&
          history.length > 0 && (
            <div>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  marginBottom: 12,
                }}
              >
                <span style={{ color: "#333", fontSize: 14 }}>最近搜索</span>
                <span
                  onClick={handleClearConfirm}
                  style={{ cursor: "pointer" }}
                >
                  <DeleteOutline
                    style={{ marginTop: 10, marginRight: 15 }}
                    fontSize={18}
                  />
                </span>
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {history.map((item) => (
                  <span
                    key={item}
                    onClick={() => handleChipClick(item)}
                    style={{
                      display: "inline-block",
                      padding: "6px 10px",
                      borderRadius: 16,
                      color: "#333",
                      fontSize: 12,
                    }}
                  >
                    {item}
                  </span>
                ))}
              </div>
            </div>
          )}

        {searchVal && (
          <Tabs
            activeKey={activeTab}
            onChange={handleTabChange}
            className={style.searchBox1}
            style={{ display: !isSearching && hasResult ? "block" : "none" }}
          >
            <Tabs.Tab title="综合" key="1">
              <Zonghe
                keyword={searchVal}
                onResult={(ok) => {
                  setHasResult(ok);
                  setIsSearching(false);
                }}
                onTabChange={handleTabChange}
              />
            </Tabs.Tab>
            <Tabs.Tab title="科普" key="2">
              <Books />
            </Tabs.Tab>
            <Tabs.Tab title="医生" key="3">
              <Doctor />
            </Tabs.Tab>
            <Tabs.Tab title="医院" key="4">
              <Hospital />
            </Tabs.Tab>
            <Tabs.Tab title="药品" key="5">
              <Soco />
            </Tabs.Tab>
          </Tabs>
        )}
        {searchVal && !isSearching && !hasResult && (
          setInterval(()=>{
            <Empty
            style={{ padding: "64px 0", marginTop: 100 }}
            image={
              <QuestionCircleOutline
                style={{
                  color: "var(--adm-color-light)",
                  fontSize: 50,
                }}
              />
            }
            description="暂无数据"
          />
          },2000)
        )}
      </div>
    </div>
  );
}

export default Index;
